package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Component
public class IllegalCharFilter extends ZuulFilter {
    @Value("${illegal_char}")
    private String illegalChar;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //具体过滤器业务代码
        System.out.println("进入了非法字符过滤器。。。");
        //获取zuul中提供的上下文对象
        RequestContext requestContext=RequestContext.getCurrentContext();
        //获取request  response
        HttpServletRequest request=requestContext.getRequest();
        HttpServletResponse response=requestContext.getResponse();
        //获取请求的参数名称集合 http://localhost:8888/ms/member/queryAll?a=1&b=2&c=3&aa=11
        //parameterNames = [a,b,c,aa]
        Enumeration<String > parameterNames = request.getParameterNames();
        //解析配置的非法字符串illegalCharArray=[sb,nnd,tmd]
        String[] illegalCharArray=illegalChar.split(",");
        //循环遍历所有参数
        while(parameterNames.hasMoreElements()){
            //第一次 a 第二次 b 。。。。
            String parameterName=parameterNames.nextElement();
            //根据名称获取值 parameterValue 第一次 1 第二次 2 。。。
            String parameterValue=request.getParameter(parameterName);
            //判断parameterValue里面是否很有非法字符
            for (String illegalChar:illegalCharArray){
                if (parameterValue.contains(illegalChar)){
                    //阻止程序运行
                    requestContext.setSendZuulResponse(false);
                    response.setCharacterEncoding("utf-8");
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN,"您的请求中含有非法参数");
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
